{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "由于函数也是一个对象，而且函数对象可以被赋值给变量，所以，通过变量也能调用该函数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2015-3-25\n"
     ]
    }
   ],
   "source": [
    "def now():\n",
    "    print('2015-3-25')\n",
    "\n",
    "f = now\n",
    "f()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "函数对象有一个 __ name __ 属性，可以拿到函数的名字："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'now'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "now.__name__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'now'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "f.__name__"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，假设我们要增强now()函数的功能，比如，在函数调用前后自动打印日志，但又不希望修改now()函数的定义，__这种在代码运行期间动态增加功能的方式，称之为“装饰器”（Decorator）__。\n",
    "\n",
    "本质上，decorator就是一个返回函数的高阶函数。所以，我们要定义一个能打印日志的decorator，可以定义如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def log(func):\n",
    "    def wrapper(*args, **kw):\n",
    "        print('call %s():' % func.__name__)\n",
    "        return func(*args, **kw)\n",
    "    return wrapper"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "观察上面的log，因为它是一个decorator，所以接受一个函数作为参数，并返回一个函数。我们要借助Python的@语法，把decorator置于函数的定义处：`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "@log\n",
    "def now():\n",
    "    print('2015-3-25')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "调用now()函数，不仅会运行now()函数本身，还会在运行now()函数前打印一行日志："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "call now():\n",
      "2015-3-25\n"
     ]
    }
   ],
   "source": [
    "now()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "把@log放到now()函数的定义处，相当于执行了语句："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "now = log(now)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "由于log()是一个decorator，返回一个函数，所以，原来的now()函数仍然存在，只是现在同名的now变量指向了新的函数，于是调用now()将执行新函数，即在log()函数中返回的wrapper()函数。\n",
    "\n",
    "wrapper()函数的参数定义是(*args, **kw)，因此，wrapper()函数可以接受任意参数的调用。在wrapper()函数内，首先打印日志，再紧接着调用原始函数。\n",
    "\n",
    "如果decorator本身需要传入参数，那就需要编写一个返回decorator的高阶函数，写出来会更复杂。比如，要自定义log的文本："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "def log(text):\n",
    "    def decorator(func):\n",
    "        def wrapper(*args, **kw):\n",
    "            print('%s %s():' % (text, func.__name__))\n",
    "            return func(*args, **kw)\n",
    "        return wrapper\n",
    "    return decorator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "execute now():\n",
      "2015-3-25\n"
     ]
    }
   ],
   "source": [
    "# 这个3层嵌套的decorator用法如下：\n",
    "@log('execute')\n",
    "def now():\n",
    "    print('2015-3-25')\n",
    "\n",
    "# 执行结果：\n",
    "now()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 和两层嵌套的decorator相比，3层嵌套的效果是这样的：\n",
    "now = log('execute')(now)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们来剖析上面的语句，首先执行log('execute')，返回的是decorator函数，再调用返回的函数，参数是now函数，返回值最终是wrapper函数。\n",
    "\n",
    "以上两种decorator的定义都没有问题，但还差最后一步。因为我们讲了函数也是对象，它有__name__等属性，但你去看经过decorator装饰之后的函数，它们的__name__已经从原来的'now'变成了'wrapper'："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'wrapper'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "now.__name__"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "因为返回的那个wrapper()函数名字就是'wrapper'，所以，需要把原始函数的__name__等属性复制到wrapper()函数中，否则，有些依赖函数签名的代码执行就会出错。\n",
    "\n",
    "不需要编写wrapper.__name__ = func.__name__这样的代码，Python内置的functools.wraps就是干这个事的，所以，一个完整的decorator的写法如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "import functools\n",
    "\n",
    "def log(func):\n",
    "    @functools.wraps(func) # wrapper.__name__ = func.__name__\n",
    "    def wrapper(*args, **kw):\n",
    "        print('call %s():' % func.__name__)\n",
    "        return func(*args, **kw)\n",
    "    return wrapper"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "或者针对带参数的decorator："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "import functools\n",
    "\n",
    "def log(text):\n",
    "    def decorator(func):\n",
    "        @functools.wraps(func)\n",
    "        def wrapper(*args, **kw):\n",
    "            print('%s %s():' % (text, func.__name__))\n",
    "            return func(*args, **kw)\n",
    "        return wrapper\n",
    "    return decorator"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 练习\n",
    "请设计一个decorator，它可作用于任何函数上，并打印该函数的执行时间："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "fast executed in 0.0029926300048828125 ms\n",
      "slow executed in 0.12402820587158203 ms\n"
     ]
    }
   ],
   "source": [
    "import time, functools\n",
    "def metric(fn):\n",
    "    @functools.wraps(fn)\n",
    "    def measure_time(*args, **kwargs):\n",
    "      start_time = time.time()\n",
    "      result = fn(*args, **kwargs)\n",
    "      end_time = time.time()\n",
    "      print('%s executed in %s ms' % (fn.__name__, end_time-start_time))\n",
    "      return result\n",
    "    return measure_time\n",
    "\n",
    "# 测试\n",
    "@metric\n",
    "def fast(x, y):\n",
    "    time.sleep(0.0012)\n",
    "    return x + y;\n",
    "\n",
    "@metric\n",
    "def slow(x, y, z):\n",
    "    time.sleep(0.1234)\n",
    "    return x * y * z;\n",
    "\n",
    "f = fast(11, 22)\n",
    "s = slow(11, 22, 33)\n",
    "if f != 33:\n",
    "    print('测试失败!')\n",
    "elif s != 7986:\n",
    "    print('测试失败!')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
